package com.dji.sample.map.controller;


import com.dji.sample.common.model.ResponseResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author yjt
 * @date 2022-11-07
 * @description:
 */
@RestController
@RequestMapping("${url.map.prefix}${url.map.version}/webOdm")
public class WebOdmUtilController {

    private static String WEB_ODM_DOMAIN = "http://192.168.49.146:8000/";

    @RequestMapping("image/{lng}/{lat}/{zoom}")
    public ResponseResult<?> trans(HttpServletResponse servletResponse, @PathVariable(name = "lng") String lng, @PathVariable(name = "lat") String lat, @PathVariable(name = "zoom") String zoom, @RequestParam String key, @RequestParam String sessionid, @RequestParam String csrftoken) throws IOException {
        String path = String.format("%s%s%s%s%s%s%s%s", WEB_ODM_DOMAIN, "api/projects/1/tasks/", key, "/orthophoto/tiles", "/" + lng, "/" + lat, "/"+zoom, "?rescale=0,255&size=512");
        String cookie= String.format("%s%s%s%s","sessionid=",sessionid,";csrftoken=",csrftoken);
        request(servletResponse,path,cookie);
        return ResponseResult.success("");
    }


    public void request(HttpServletResponse httpServletResponse,String path,String cookie) {
        HttpURLConnection con = null;
        try {
            URL url = new URL(path);
            //得到连接对象
            con = (HttpURLConnection) url.openConnection();
            //设置请求类型
            con.setRequestMethod("GET");
            //设置Content-Type，此处根据实际情况确定
            con.setRequestProperty("Cookie", cookie);
            //允许写出
            con.setDoOutput(true);
            //允许读入
            con.setDoInput(true);
            //不使用缓存
            con.setUseCaches(false);
            //得到响应码
            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                //得到响应流
                InputStream inputStream = con.getInputStream();
                ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
                servletOutputStream.write(inputStream.readAllBytes());
                servletOutputStream.flush();
                inputStream.close();
                servletOutputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


